package cn.liuxue.lifecircle.media;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MediaActivity extends Activity implements SurfaceHolder.Callback {
	
	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;
	private MediaPlayer mp;
	
	
	private void playVideo() {
		
		try {
			mp = new MediaPlayer();
			//video in asset
			AssetFileDescriptor afd = this.getAssets().openFd("");
			FileDescriptor fd = afd.getFileDescriptor();
			mp.setDataSource(fd, afd.getStartOffset(), afd.getLength());
			afd.close();
			
			//video in sdcard
			
			File sdFile = Environment.getExternalStorageDirectory();
			mp.setDataSource(sdFile.getAbsolutePath() + File.separator + "");
			
			//video in res
			
//			mp.setDataSource(this, R.raw.welcome);
			
			
			
			mp.setDisplay(surfaceHolder);
			mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
			
			mp.prepare();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mp.start();
		
	}
	
	

	@SuppressLint("ParserError")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.surfaceView = new SurfaceView(this);
		this.surfaceHolder = surfaceView.getHolder();
		this.surfaceHolder.addCallback(this);
		this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		setContentView(this.surfaceView);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (this.mp != null) {
			this.mp.release();
			this.mp = null;
		}
	}



	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		 playVideo();
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		
	}

}
